import { ESTerrainLayer,ESVisualObject, ESJEditingMode, ESJVector4D } from "earthsdk3";
import { SceneObjectKey, UniteChanged, reactArray, reactJsonWithUndefined, track } from "earthsdk3";

/**
 * TerrainRTS 
 */
export class ESRTSTerrainLayer extends ESVisualObject {
    static createDefaultProps = () => ({
        ...ESVisualObject.createDefaultProps(), 
        url: "",
        rectangle: reactArray<ESJVector4D>([-180, -90, 180, 90]),
    });
    static override readonly type: string = this.register('ESRTSTerrainLayer', this, { chsName: 'TerrainRTS实时3DTileset图层', tags: ['ESObjects', '_ES_Impl_Cesium', '_ES_Impl_UE'], description: "地理多边形体" });


    /**
     * 内部的 ESTerrainLayer 实例。
     */
    private _eSTerrainLayer = this.dv(new ESTerrainLayer());

    /**
     * 获取内部的 ESTerrainLayer 实例。
     * @returns 内部的 ESTerrainLayer 实例。
     */
    get eSTerrainLayer() { return this._eSTerrainLayer; }

    /**
   * 获取当前服务的基础 URL。
   * @returns 当前服务的基础 URL。
   */
    get baseUrl() {
        if (this.url && typeof this.url === 'string') {
            const uri = this.url.match(/^(https?:\/\/[^\/]+)/)?.[1];
            if (!uri) {
                throw new Error('服务地址不合法,baseUrl is not found! 示例: http://localhost:9209/ts/info/ts01');
            }
            return uri;
        } else {
            throw new Error('服务地址不合法,baseUrl is not found! 示例: http://localhost:9209/ts/info/ts01');
        }
    }

    /**
   * 获取图层服务名称。
   * @returns 图层服务名称。
   */
    get tileServiceName() {
        if (this.url && typeof this.url === 'string') {
            const u1 = this.url.match(/\/ts\/info\/(.*)/)?.[1]
            if (!u1) {
                console.log(this.url);
                throw new Error('服务地址不合法,tileServiceName is not found! 示例: http://localhost:9209/ts/info/ms01,');
            }
            return u1
        } else {
            throw new Error('服务地址不合法,tileServiceName is not found! 示例: http://localhost:9209/ts/info/ms01');
        }
    }

    /**
     * 刷新图层。
     */
    async refresh() {
        if (!this.url || typeof this.url !== 'string') return;
        const baseUrl = this.baseUrl;//http://localhost:9209
        const tileServiceName = this.tileServiceName; //ms01
        const time = +new Date();
        this._eSTerrainLayer.url = `${baseUrl}/terrain/${tileServiceName}/layer.json` + `?t=${time}`;
        console.log('eSTerrainLayer url:', this._eSTerrainLayer.url);
    }


    constructor(id?: SceneObjectKey) {
        super(id);

        {
            const loadTileset = async () => {
                if (typeof this.url !== 'string') {
                    console.error('服务地址不合法, Init Error! 示例: http://localhost:9209/ts/info/ts01');
                    return;
                }
                if (!this.url) {
                    this._eSTerrainLayer.url = ""
                } else {
                    this.refresh();
                }
            }
            // loadTileset();
            this.d(this.urlChanged.don(() => { loadTileset() }));
        }

        //属性同步
        {
            this.d(this.components.disposableAdd(this._eSTerrainLayer));
            const eSTerrainLayer = this._eSTerrainLayer;
            this.d(track([eSTerrainLayer, 'show'], [this, 'show']));
            this.d(track([eSTerrainLayer, 'name'], [this, 'name']));
            // this.d(track([eSTerrainLayer, 'rectangle'], [this, 'rectangle']));

        }

        //函数同步
        {
            const eSTerrainLayer = this._eSTerrainLayer;
            this.d(this.flyInEvent.don((...arg) => { eSTerrainLayer.flyIn(arg[0]); }));
            this.d(this.flyToEvent.don((...arg) => { eSTerrainLayer.flyTo(arg[0]); }));
        }
    }
}

export interface ESRTSTerrainLayer extends UniteChanged<ReturnType<typeof ESRTSTerrainLayer.createDefaultProps>> { }
